/**
 * 基于 axios 封装的请求模块
 * **/
import axios, {AxiosResponse, InternalAxiosRequestConfig} from 'axios'
import Authorization from './headers'
import useUserStore from "@/store/user";
import {ElMessage} from "element-plus";


// 创建一个 axios 实例
const request = axios.create({
  baseURL: import.meta.env.VITE_HTTP, // 请求的基础路径
})

// 拦截器：请求拦截器
request.interceptors.request.use(
  // 所有请求会经过这里
  (config:InternalAxiosRequestConfig) => {
    config.headers.Authorization = Authorization()
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  // 请求失败，会经过这里
  err => {
    console.log('请求失败:', err)
    return Promise.reject(err)
  }
)
// 拦截器：响应拦截器
request.interceptors.response.use(
  (config:AxiosResponse) => {
    return config
  },
  err => {
    return Promise.reject(err)
  },
)

request.interceptors.response.use(response => {
  switch (response.data.code) {
    case 200:
      // ElMessage.success(response.data.msg)
      break
    case 401:
      ElMessage.warning('登录状态失效，请重新登录')
      useUserStore().logout()
      location.reload()
      break;
    default:
      ElMessage.error(response.data.msg)
  }
  return response
  }
)
export default request
